package com.gaga.console.base.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class RestUtils {
    private static int connectTimeout = 3000;
    private static int readTimeout = 30000;

    @Value("${feign.client.config.default.connectTimeout:3000}")
    public void setConnectTimeout(int value) {
        connectTimeout = value;
    }

    @Value("${feign.client.config.default.readTimeout:30000}")
    public void setReadTimeout(int value) {
        readTimeout = value;
    }

    public static String get(String url) {
        return get(url, new HashMap<>());
    }

    public static String get(String url, Map<String, Object> headMap) {
        Long startTime = System.currentTimeMillis();

//        String params = encodeParams(headMap);
        // Hutool 自动处理 URL 编码和参数拼接
        HttpRequest httpRequest = HttpUtil.createGet(url);
        httpRequest.setReadTimeout(readTimeout);
        httpRequest.setConnectionTimeout(connectTimeout);

        return getResultString(startTime, null, httpRequest);
    }


    public static String post(String url, String json) {
        return post(url, json, new HashMap<>());
    }

    public static String post(String url, Map<String, Object> params, Map<String, Object> headMap) {
        return post(url, JSON.toJSONString(params), headMap);
    }

    public static String post(String url, String json, Map<String, Object> headMap) {
        Long startTime = System.currentTimeMillis();
        log.info("url:{}, params:{}", url, json);
        HttpRequest httpRequest = HttpUtil.createPost(url);
        httpRequest.setReadTimeout(readTimeout * 1000);
        httpRequest.setConnectionTimeout(connectTimeout * 1000);
        if (MapUtils.isNotEmpty(headMap)) {
            setHeaders(httpRequest, headMap);
        }
        httpRequest.body(json);

        return getResultString(startTime, json, httpRequest);
    }

    @NotNull
    private static String getResultString(Long startTime, String params, HttpRequest httpRequest) {
        log.error("发起请求的参数信息：url:{},header:{}, params:{}", httpRequest.getUrl(), JSON.toJSONString(httpRequest.headers()), params);
        try (HttpResponse response = httpRequest.execute()) {
            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("失败的参数信息：url:{},header:{}, params:{}", httpRequest.getUrl(), JSON.toJSONString(httpRequest.headers()), params);
            log.error(e.getMessage(), e);
            Long exceptTime = System.currentTimeMillis();
            log.error("请求耗时：{}", exceptTime - startTime);
//            throw new BusException(e.getMessage());
        }
        return null;
    }

    public static String postAudio(String url, String json, Map<String, Object> headMap, String savePath) {
        Long startTime = System.currentTimeMillis();
        log.error("=====tts请求url:{}, params:{}", url, json);
        HttpRequest httpRequest = HttpUtil.createPost(url);
        httpRequest.setReadTimeout(readTimeout * 1000);
        httpRequest.setConnectionTimeout(connectTimeout * 1000);
        if (MapUtils.isNotEmpty(headMap)) {
            setHeaders(httpRequest, headMap);
        }
        httpRequest.body(json);

        return getAudioResult(startTime, json, httpRequest, savePath);
    }

    @NotNull
    private static String getAudioResult(Long startTime, String params, HttpRequest httpRequest, String savePath) {
        log.error("发起请求的参数信息：url:{},header:{}, params:{}", httpRequest.getUrl(), JSON.toJSONString(httpRequest.headers()), params);
        try (HttpResponse response = httpRequest.execute()) {
            // 先检查响应状态
            if (!response.isOk()) {
                // 读取错误响应体内容
                String errorBody = response.body();
                log.error("请求失败，状态码: {}，错误原因: {}", response.getStatus(), errorBody);
                return null;
            }

            // 状态正常，处理音频流
            try (InputStream inputStream = response.bodyStream();
                 BufferedInputStream bis = new BufferedInputStream(inputStream);
                 FileOutputStream fos = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                log.error("音频已保存到: {}", savePath);
            }
        } catch (Exception e) {
            log.error("请求失败 | URL: {}, Header: {}, 耗时: {}ms, 错误信息: {}",
                    httpRequest.getUrl(),
                    JSON.toJSONString(httpRequest.headers()),
                    System.currentTimeMillis() - startTime,
                    e.getMessage(), e);
            throw new RuntimeException(e);
        }
        log.error("tts请求耗时: {}ms", System.currentTimeMillis() - startTime);
        return savePath;
    }

    public static void setHeaders(HttpRequest httpRequest, Map<String, Object> headersParams) {
        if (MapUtils.isNotEmpty(headersParams)) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next();
                httpRequest.header(key, headersParams.get(key).toString());
            }
        }
    }

}
